package com.wu.handler;

import com.wu.flandre_common.entity.RpcRequest;
import com.wu.flandre_common.entity.RpcResponse;
import com.wu.flandre_common.property.Constants;
import com.wu.flandre_common.util.CommonUtil;
import com.wu.flandre_common.util.RpcRestTemp;
import lombok.extern.slf4j.Slf4j;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Properties;

/**
 * EngineMailHandler <br/>
 *
 * @author 50816 <br/>
 * @date 2019/12/22 20:14 <br/>
 */
@Slf4j
public class EngineMailHandler {

    private Session getMailSession() {
        Properties props = new Properties();
        props.put("mail.smtp.host", Constants.HOST);
        props.put("mail.smtp.auth", "true");
        props.put("mail.user", Constants.MAIL_SENDER);
        props.put("mail.password", Constants.MAIL_CODE);
        props.put("mail.smtp.port", 465);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        return Session.getInstance(props);
    }


    public RpcResponse verificationCode(RpcRequest request) {
        RpcResponse response = null;
        EngineMailHandler mailHandler = new EngineMailHandler();
        Session mailSession = mailHandler.getMailSession();
        Message mail = new MimeMessage(mailSession);
        try {
            mail.setSubject(Constants.LOGIN_MAIL_TITLE);
            mail.setFrom(new InternetAddress(Constants.MAIL_SENDER, "Flandre", Constants.MAIL_ENCODING));
            mail.setSentDate(new Date());
            Integer code = CommonUtil.getInstance().getRandomSixNumber();
            String text = MessageFormat.format(Constants.LOGIN_MAIL_CONTENT, code);
            mail.setContent(text, "text/html;charset=utf8");
            Transport transport = mailSession.getTransport("smtp");
            transport.connect(Constants.HOST, Constants.MAIL_SENDER, Constants.MAIL_CODE);
            transport.sendMessage(mail, new Address[]{new InternetAddress(request.getData().toString())});
            response = RpcRestTemp.success(null);
        } catch (Exception e) {
            log.error("引擎执行发送注册邮件任务异常:" + e.getMessage());
            e.printStackTrace();
            response = RpcRestTemp.error();
        }
        return response;
    }
}
